<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 登录账号 -->
        <div class="form-item">
            <label class="form-label">登录账号：</label>
            <input type="text"
                   class="form-input"
                   placeholder="登录账号">
        </div>

        <!-- 姓名 -->
        <div class="form-item">
            <label class="form-label">姓名：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入姓名">
        </div>

        <!-- 角色 -->
        <div class="form-item">
            <label class="form-label">角色：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入角色">
        </div>

        <!-- 部门 -->
        <div class="form-item">
            <label class="form-label">部门：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入部门">
        </div>

        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">状态：</label>
            <select class="form-input form-select form-select">
                <option value="">全部</option>
                <option value="1">启用中</option>
                <option value="0">禁用中</option>
                <option value="2">审核中</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">

        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
        <button class="btn btn-export">导出Excel</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>账号</th>
            <th>姓名</th>
            <th>所属角色</th>
            <th>所属部门</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增用户
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-add">
            <!-- 基础信息模块 -->
            <div class="form-section">
                <h4 class="form-subtitle">* 基础信息</h4>

                <!-- 登录账号 -->
                <div class="form-item">
                    <label>* 登录账号：</label>
                    <input  type="text"
                            id="account"
                            placeholder="请输入登录账号"
                           required>
                </div>

                <!-- 登录密码 -->
                <div class="form-item">
                    <label>* 登录密码：</label>
                    <input type="password"
                           id="password"
                           placeholder="请输入登录密码"
                           required>
                </div>

                <!-- 所属部门 -->
                <div class="form-item">
                    <label>* 所属部门：</label>
                    <select required id="pc-depart-select">
                        <option value="">请选择部门</option>
                        <!-- 动态填充部门选项 -->
                    </select>
                </div>

                <!-- PC角色 -->
                <div class="form-item">
                    <label>* PC所属角色：</label>
                    <select required id="pc-role-select" >
                        <option value="">请选择角色</option>
                        <!-- 动态填充角色选项 -->
                    </select>
                </div>

                <!-- 服务港口 -->
                <div class="form-item">
                    <label>服务港口：</label>
                    <div class="multi-select">
                        <div class="selected-box" id="select-port">
                            <span class="placeholder">请选择服务港口</span>
                            <div class="selected-items"></div>
                        </div>
                        <div class="options-container" id="pc-port-options">
                            <!-- 动态填充选项 -->
                        </div>
                        <span class="error-msg" style="color: red; display: none;">请至少选择一个港口</span>
                        <input type="hidden" id="pc-port-select" name="essPort">
                    </div>
                </div>

                <!-- 员工姓名 -->
                <div class="form-item">
                    <label>* 员工姓名：</label>
                    <input type="text"
                           id="empNm"
                           placeholder="请输入员工姓名"
                           required>
                </div>

                <!-- 邮箱 -->
                <div class="form-item">
                    <label>邮箱：</label>
                    <input type="email"
                           id="email"
                           placeholder="请输入邮箱">
                </div>

                <!-- 性别 -->
                <div class="form-item">
                    <label>性别：</label>
                    <div class="radio-group">
                        <label>
                            <input type="radio" name="gender" value="0">
                            男
                        </label>
                        <label>
                            <input type="radio" name="gender" value="1">
                            女
                        </label>
                    </div>
                </div>

                <!-- 年龄 -->
                <div class="form-item">
                    <label>年龄：</label>
                    <input type="number"
                           id="age"
                           placeholder="请输入用户年龄"
                           min="1">
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">新增</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask modal-mask-update" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改用户
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-update">
            <!-- 基础信息模块 -->
            <input type="hidden" id="userId" name="id">
            <div class="form-section">
                <h4 class="form-subtitle">* 基础信息</h4>
                <!-- 所属部门 -->
                <div class="form-item">
                    <label>* 所属部门：</label>
                    <select required id="pc-depart-select-update" >
                        <option value="">请选择部门</option>
                        <!-- 动态填充部门选项 -->
                    </select>
                </div>

                <!-- PC角色 -->
                <div class="form-item">
                    <label>* PC所属角色：</label>
                    <select required id="pc-role-select-update" class="pc-role-select">
                        <option value="">请选择角色</option>
                        <!-- 动态填充角色选项 -->
                    </select>
                </div>

                <!-- 服务港口 -->
                <div class="form-item">
                    <label>服务港口：</label>
                    <div class="multi-select">
                        <div class="selected-box" id="select-port-update">
                            <span class="placeholder">请选择服务港口</span>
                            <div class="selected-items"></div>
                        </div>
                        <div class="options-container" id="pc-port-options-update"></div>
                        <input type="hidden" id="pc-port-select-update" name="essPort">
                    </div>
                </div>

                <!-- 员工姓名 -->
                <div class="form-item">
                    <label>* 员工姓名：</label>
                    <input type="text"
                           id="empNm-update"
                           placeholder="请输入员工姓名"
                           required>
                </div>

                <!-- 邮箱 -->
                <div class="form-item">
                    <label>邮箱：</label>
                    <input type="email"
                           id="email-update"
                           placeholder="请输入邮箱">
                </div>

                <!-- 性别 -->
                <div class="form-item">
                    <label>性别：</label>
                    <div class="radio-group">
                        <label>
                            <input type="radio" name="gender" value="0">
                            男
                        </label>
                        <label>
                            <input type="radio" name="gender" value="1">
                            女
                        </label>
                    </div>
                </div>

                <!-- 年龄 -->
                <div class="form-item">
                    <label>年龄：</label>
                    <input type="number"
                           id="age-update"
                           placeholder="请输入用户年龄"
                           min="1">
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">修改</button>
            </div>
        </form>
    </div>
</div>
<!-- 用户详情弹窗 -->
<div class="modal-mask" id="modal-mask-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            用户详情
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <!-- 基础信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">用户状态：</span>
                    <span id="detail-status" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">用户姓名：</span>
                    <span id="detail-empNm" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">手机号：</span>
                    <span id="detail-phone" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">邮箱：</span>
                    <span id="detail-email" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">性别：</span>
                    <span id="detail-gender" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">年龄：</span>
                    <span id="detail-age" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">服务港口：</span>
                    <div id="detail-ports" class="detail-value"></div>
                </div>
                <div class="detail-row">
                    <span class="detail-label">所属部门：</span>
                    <span id="detail-department" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">PC角色：</span>
                    <span id="detail-role" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">创建时间：</span>
                    <span id="detail-createTime" class="detail-value"></span>
                </div>
            </div>

            <!-- 操作记录 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs" class="detail-logs">
                    暂无数据
                </div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')

    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');
            let status
            item.status = parseInt(item.status)
            if(item.status ===1){
                status ='启用中'
            }else if (item.status ===0){
                status ='禁用中'
            }else if (item.status ===2){
                status='审核中'
            }else {
                item.status=''
            }

            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.account}</td>
                <td>${item.empNm}</td>
                <td>${item.roleNm || ''}</td>
                <td>${item.depNm || ''}</td>
                <td>${status}</td>
                <td>
                    <button class="table-disable-btn">禁用</button>
                     <button class="table-detail-btn">详情</button>
                    <button class="table-edit-btn">修改</button>
                    <button class="table-delete-btn">重置密码</button>
                </td>
    `;

            // 绑定操作按钮事件
            const disableBtn = tr.querySelector('.table-disable-btn');
            // 在forEach循环中添加以下代码
            const detailBtn = tr.querySelector('.table-detail-btn');
            const editBtn = tr.querySelector('.table-edit-btn');
            const resetPasswordBtn = tr.querySelector('.table-delete-btn');
            if(item.status ===1){
                disableBtn.textContent ='禁用'
            }else if (item.status ===0){
                disableBtn.textContent ='启用'
            }
            // 禁用/启用切换
            disableBtn.addEventListener('click', () => disableUser(item.id, item.status));
            item.status = parseInt(item.status)
            detailBtn.addEventListener('click', () => showUserDetail(item));

            // 修改功能
            editBtn.addEventListener('click', () => updateUser(item));

            // 重置密码功能
            resetPasswordBtn.addEventListener('click', () => resetUserPassword(item));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            account: document.querySelector('input[placeholder="登录账号"]').value,
            empNm: document.querySelector('input[placeholder="请输入姓名"]').value,
            roleNm: document.querySelector('input[placeholder="请输入角色"]').value,
            depNm: document.querySelector('input[placeholder="请输入部门"]').value,
            status: document.querySelector('.form-select').value,
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/user/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '' // 清空文本输入
            if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        });

    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click',async  () => {

        document.querySelector('#modal-mask-add').style.display = 'flex'
        try {
            selectAllRole();
            selectAllDepartment();
            selectAllSupplierPort();
        } catch (error) {
            console.error('加载失败:', error);
            // 可以添加错误提示
            // alert('角色数据加载失败，请刷新页面');
        }
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理modal-form-add
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault()
        const formData = {
            account: document.getElementById('account').value,
            password: document.getElementById('password').value,
            depId: document.getElementById('pc-depart-select').value,    // 部门ID
            roleId: document.getElementById('pc-role-select').value,     // 角色ID
            empNm: document.getElementById('empNm').value,               // 员工姓名
            email: document.getElementById('email').value,               // 邮箱
            empGender: document.querySelector('input[name="gender"]:checked')?.value || '', // 性别
            age: document.getElementById('age').value,                   // 年龄
            employeePorts: document.getElementById('pc-port-select').value
                .split(',')
                .filter(id => id) // 过滤空值
                .map(id => ({ portId: id })) // 转换数据结构
        };

        try {
            const response = await fetch('http://localhost:8080/user/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();
            console.log(data.data)
            console.log((data.status)===0)
            if((data.status)===0) {
                alert("添加成功")
                document.querySelector('.modal-mask').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        } catch(err) {
            console.error('提交失败:', err)
        }
    })
    document.querySelector('#modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault()
        console.log(e)
        const formData = {
            id: document.getElementById('userId').value, // [1,3](@ref)
            depId: document.getElementById('pc-depart-select-update').value,    // 部门ID
            roleId: document.getElementById('pc-role-select-update').value,     // 角色ID
            empNm: document.getElementById('empNm-update').value,               // 员工姓名
            email: document.getElementById('email-update').value,               // 邮箱
            empGender: document.querySelector('input[name="gender"]:checked')?.value || '', // 性别
            age: document.getElementById('age-update').value,                   // 年龄
            employeePorts: document.getElementById('pc-port-select-update').value
                .split(',')
                .filter(id => id) // 过滤空值
                .map(id => ({ portId: id })) // 转换数据结构
        };

        try {
            const response = await fetch('http://localhost:8080/user/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();

            if((data.status)===0) {
                alert("修改成功")
                document.querySelector('.modal-mask-update').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        } catch(err) {
            console.error('提交失败:', err)
        }
    })
    //表格函数

    async function showUserDetail(item) {
        const modal = document.getElementById('modal-mask-detail');

        // try {
            const res = await fetch(`http://localhost:8080/user/detail/${item.id}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const  response  = await res.json(); // 解构data字段

            if ( parseInt(response.status) === 0){
                const data = response.data;
                console.log( data)
            // 3. 基础信息绑定（匹配JSON字段）
            document.getElementById('detail-status').textContent =
                data.status === 1 ? '启用中' :  data.status === 0 ? '禁用中' : '审核中';
            // document.getElementById('detail-account').textContent = data.account || '--';
            document.getElementById('detail-empNm').textContent = data.empNm || '--';
            document.getElementById('detail-email').textContent = data.email || '未填写';
            document.getElementById('detail-gender').textContent =
                data.empGender === '0' ? '男' : data.empGender === '1' ? '女' : '--';
            document.getElementById('detail-age').textContent = data.age ?? '--';
            document.getElementById('detail-department').textContent = data.depNm || '--';
            document.getElementById('detail-role').textContent = data.roleNm || '--';
            document.getElementById('detail-createTime').textContent =
                data.createTime ? formatDateTime(data.createTime) : '--';
            // 4. 服务港口渲染（字段修正）
            const portNames = data.employeePorts?.map(p => p.portName).join(', ') || '--';
            document.getElementById('detail-ports').textContent = portNames;

            // 5. 操作记录动态渲染
            const logsContainer = document.getElementById('detail-operationLogs');
            logsContainer.innerHTML = data.operateRecordList?.length > 0 ?
                data.operateRecordList.map(log => `
                <div class="log-item">
                    <span>${log.createTime || '无时间'}</span>
                    <span class="log-type">${log.operateType}</span>
                </div>
            `).join('') : '<div class="no-data">暂无操作记录</div>';

            modal.style.display = 'flex';
            }
        // } catch (err) {
        //     console.error('详情加载失败:', err);
        //     alert(`加载失败: ${err.message}`);
        // }
    }

    // 绑定关闭事件（添加到已有的事件监听代码中）
    document.querySelector('#modal-mask-detail .modal-close-btn').addEventListener('click', () => {
        document.getElementById('modal-mask-detail').style.display = 'none';
    });
    document.querySelector('#modal-mask-detail .btn-close').addEventListener('click', () => {
        document.getElementById('modal-mask-detail').style.display = 'none';
    });

    async function disableUser(id, currentStatus) {
        const newStatus = currentStatus === 1 ? 0 : 1;

        try {
            const res = await fetch(`http://localhost:8080/user/disable`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id, status: newStatus })
            });
            const data = await res.json();

            if(data.status === 0) {
                alert(`已${newStatus === 1 ? '启用' : '禁用'}`);
                fetchData('query');
            }
        } catch(err) {
            console.error('状态修改失败:', err);
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    async function updateUser(item) {
        const modal = document.getElementById('modal-mask-update');
        modal.style.display = 'flex';

        try {
            await Promise.all([selectAllRole(), selectAllDepartment(), selectAllSupplierPort()]);

            // 设置用户ID到隐藏字段
            document.getElementById('userId').value = item.id; // [1,2](@ref)

            // 设置部门
            document.getElementById('pc-depart-select-update').value = item.depId;
            // 设置角色
            document.getElementById('pc-role-select-update').value = item.roleId;
            // 设置港口
            const portIds = item.employeePorts?.map(p => p.portId) || [];
            document.querySelectorAll('#pc-port-options-update .checkbox-ports').forEach(cb => {
                cb.checked = portIds.includes(cb.value);
            });
            updateSelectedItems('pc-port-options-update');

            // 设置其他字段
            document.getElementById('empNm-update').value = item.empNm;
            document.getElementById('email-update').value = item.email || '';
            document.querySelector(`#modal-form-update input[name="gender"][value="${item.empGender}"]`).checked = true;
            document.getElementById('age-update').value = item.age || '';
        } catch (error) {
            console.error('加载数据失败:', error);
        }
    }

    async function resetUserPassword(item) {

        const isConfirmed = confirm(`是否确认重置【${item.account}】账号密码为666666？`);

        if (isConfirmed) {
            // 构造请求参数
            const requestBody = {
                id: item.id
            };

            // 发送POST请求[9,10,11](@ref)
            const response = await fetch('http://localhost:8080/user/reset', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 如果需要认证可添加：'Authorization': 'Bearer ' + token
                },
                body: JSON.stringify(requestBody)
            })
            try{
                const data = await response.json();
                if (data.status === 0) {
                    alert("密码重置成功！");
                    // 刷新表格数据（假设你有refreshData函数）
                    fetchData('query');
                } else {
                    alert(`重置失败：${data.message}`);
                }
            }catch(err) {
                console.error('提交失败:', err)
            }
        } else {
            console.log("用户取消操作");
        }
    }

    function fillSelectOptions(selectId, data, textKey) {
        const select = document.getElementById(selectId);
        while (select.options.length > 1) select.remove(1); // 保留默认选项
        data.forEach(item => {
            const option = document.createElement('option');
            option.value = item.id;
            option.textContent = item[textKey];
            select.appendChild(option);
        });
    }

    function fillPortOptions(ports, containerId) {
        const container = document.getElementById(containerId);
        container.innerHTML = '';
        ports.forEach(port => {
            const label = document.createElement('label');
            label.className = 'option-item';
            label.innerHTML = `
            <input type="checkbox" class="checkbox-ports" value="${port.id}">
            <div class="checkbox-ports-text">${port.supplier_name}</div>
        `;
            label.querySelector('input').addEventListener('change', () => updateSelectedItems(containerId));
            container.appendChild(label);
        });
    }

    async function selectAllRole(){
        const response = await  fetch('http://localhost:8080/role/selectAllRole', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        const data = await  response.json();

        if (data.status === 0) {
            fillSelectOptions('pc-role-select', data.data, 'role_nm');
            fillSelectOptions('pc-role-select-update', data.data, 'role_nm');
        }
    }

    async function selectAllDepartment(){
        const response = await  fetch('http://localhost:8080/department/selectAllDepartment', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        const data = await  response.json();

        if (data.status === 0) {
            fillSelectOptions('pc-depart-select', data.data, 'dep_nm');
            fillSelectOptions('pc-depart-select-update', data.data, 'dep_nm');
        }
    }

    async function selectAllSupplierPort(){
        const response = await  fetch('http://localhost:8080/sys/supplierPort/publicSelectPort', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        const data = await  response.json();


        if (data.status === 0) {
                fillPortOptions(data.data, 'pc-port-options');
                fillPortOptions(data.data, 'pc-port-options-update');
        }
    }

    document.getElementById('select-port').addEventListener('click',function (){
        const options = document.getElementById('pc-port-options');
        options.style.display = options.style.display === 'block' ? 'none' : 'block';
    })
    document.getElementById('select-port-update').addEventListener('click',function (){
        const options = document.getElementById('pc-port-options-update');
        options.style.display = options.style.display === 'block' ? 'none' : 'block';
    })

    function updateSelectedItems(containerId) {
        const isUpdate = containerId === 'pc-port-options-update';
        const selectedBoxId = isUpdate ? 'select-port-update' : 'select-port';
        const hiddenInputId = isUpdate ? 'pc-port-select-update' : 'pc-port-select';

        const checkboxes = document.querySelectorAll(`#${containerId} .checkbox-ports:checked`);
        const selectedItems = document.querySelector(`#${selectedBoxId} .selected-items`);
        const hiddenInput = document.getElementById(hiddenInputId);
        const placeholder = document.querySelector(`#${selectedBoxId} .placeholder`);

        placeholder.style.display = checkboxes.length ? 'none' : 'inline';
        selectedItems.innerHTML = '';
        const values = [];

        checkboxes.forEach(cb => {
            values.push(cb.value);
            const portName = cb.nextElementSibling.textContent;
            selectedItems.innerHTML += `
            <div class="selected-item">
                ${portName}
                <span class="remove-btn">×</span>
            </div>
        `;
        });

        hiddenInput.value = values.join(',');
    }
    // 新增事件委托监听（添加到现有代码中）
    // 处理移除按钮事件
    document.querySelectorAll('.selected-items').forEach(container => {
        container.addEventListener('click', e => {
            if (e.target.classList.contains('remove-btn')) {
                const item = e.target.closest('.selected-item');
                const portName = item.firstChild.textContent.trim();
                const isUpdate = container.closest('#select-port-update') !== null;
                const optionsContainer = isUpdate ? 'pc-port-options-update' : 'pc-port-options';

                document.querySelectorAll(`#${optionsContainer} .checkbox-ports`).forEach(cb => {
                    if (cb.nextElementSibling.textContent === portName) cb.checked = false;
                });
                updateSelectedItems(optionsContainer);
            }
        });
    });

    document.querySelector('.btn-export').addEventListener('click', exportData);

    async function exportData() {
        // 复用查询参数构造逻辑
        const queryParams = {
            // account: document.querySelector('input[placeholder="登录账号"]').value,
            ...(document.querySelector('input[placeholder="登录账号"]').value && {
                account: document.querySelector('input[placeholder="登录账号"]').value
            }),
            // 姓名：有值则添加，无值跳过
            ...(document.querySelector('input[placeholder="请输入姓名"]').value && {
                empNm: document.querySelector('input[placeholder="请输入姓名"]').value
            }),
            // 角色：有值则添加，无值跳过
            ...(document.querySelector('input[placeholder="请输入角色"]').value && {
                roleNm: document.querySelector('input[placeholder="请输入角色"]').value
            }),
            // 部门：有值则添加，无值跳过
            ...(document.querySelector('input[placeholder="请输入部门"]').value && {
                depNm: document.querySelector('input[placeholder="请输入部门"]').value
            }),
            ...(document.querySelector('.form-select').value !== "" && {
                status: document.querySelector('.form-select').value
            })
        };

        try {
        // 3. 发送请求（添加超时处理）
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 15000); // 15秒超时
            // 1. 将参数转换为查询字符串[4](@ref)
            const queryString = new URLSearchParams(queryParams).toString();
            const response = await fetch(`http://localhost:8080/user/userExport?${queryString}`, {
                method: 'Get',
                headers: { 'Content-Type': 'application/json' },
                signal: controller.signal
            });
        clearTimeout(timeoutId);
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`导出失败: ${response.status} - ${errorText}`);
        }

                // 处理二进制流（关键修正）
                const blob = await response.blob();
                // 6. 自动解析文件名（优先使用后端返回的文件名）
                const contentDisposition = response.headers.get('Content-Disposition');
                const filename = contentDisposition
                    ? decodeURIComponent(contentDisposition.split('filename=')[1].replace(/"/g, ''))
                    : `用户数据_${new Date().toISOString().slice(0,10)}.xlsx`;

                // 7. 创建下载链接（兼容IE的替代方案）
                if (window.navigator.msSaveBlob) {
                    // IE10+专用方法
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = filename;
                    link.style.display = 'none';

                    document.body.appendChild(link);
                    link.click();

                    // 清理资源
                    setTimeout(() => {
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(url);
                    }, 100);
                }

        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败，请检查网络连接或联系管理员');
        }
    }
</script>
</body>
</html>